exports.get = function(player, req, resp, onHandled) {
    resp.nolog = 1;
    var user = player.user;

    if( user.status.level < gConfGlobal.ServerMineOpenLevel ) {
        resp.code = 1; resp.desc = 'level not reach';
        onHandled();
        return;
    }

    req.args.server = config.ServerId - 1;
    requestServerMine(req, resp, function() {
        if( resp.code == 0 ) {
            if( resp.data.leave ) {
                user.status.gold += resp.data.leave.gold;
                player.markDirty('status.gold');
            }
        }
        onHandled();
    });
}

exports.occupy = function(player, req, resp, onHandled) {
    var user = player.user;
    
    do {
        if( user.status.level < gConfGlobal.ServerMineOpenLevel ) {
            resp.code = 1; resp.desc = 'level not reach'; break;
        }

        if( user.server_mine.free >= gConfGlobal.ServerMineDailyLimit ) {
            resp.code = 1; resp.desc = 'no more times'; break;
        }

    }while(false);

    if( resp.code != 0 ) {
        onHandled();
        return;
    }

    req.args.havegold = user.status.gold;
    req.args.server = config.ServerId - 1;
    
    player.calculateTeamRoleAttr();

    var userCopy = {};
    var fields = ['_id', 'role', 'team', 'pet', 'special_role'];
    for( var i = 0, len = fields.length; i < len; i++) {
        var field = fields[i];
        userCopy[field]  = user[field];
    }

    userCopy.info = {un: user.info.un, headpic: common.handleHeadpicParseException(user.info.headpic)};
    userCopy.status = {'level': user.status.level};
    userCopy['_role_attr'] = player.roleAttrs;

    req.args.user = userCopy;
    req.args.league = user.league.name;

    requestServerMine(req, resp, function() {
        if( resp.code == 0 ) {
            if( resp.data.gold ) {
                user.status.gold += resp.data.gold;
                player.markDirty('status.gold');
            }

            if( resp.data.occupied ) {
                user.server_mine.free += 1;
                player.markDirty('server_mine');
                player.checkEvent('DoServerMineWin');
            }
        }

        delete req.args.user;

        onHandled();
    });
}

exports.leave = function(player, req, resp, onHandled) {
    var user = player.user;
    if( user.status.level < gConfGlobal.ServerMineOpenLevel ) {
        resp.code = 1; resp.desc = 'level not reach';
        onHandled();
        return;
    }

    req.args.server = config.ServerId - 1;
    requestServerMine(req, resp, function() {
        if( resp.code == 0 ) {
            if( resp.data.gold ) {
                player.user.status.gold += resp.data.gold;
                player.markDirty('status.gold');
            }
        }

        onHandled();
    });
}

exports.get_replay = function(player, req, resp, onHandled) {
    requestServerMine(req, resp, onHandled);
}
